var fs = require('fs')
var postPath = require('../config/pathConfig').postPath
var util = require('../utility/util.js')

var safePathCheck = util.safePathCheck

var Active = require('./activeHandler')

module.exports = {
  insert: function (filter, content, callback) {
    var userId = filter.userId, postId = filter.postId, commentId = filter.commentId
    var fileName = userId + '-' + postId + '.data'
    safePathCheck(postPath, fileName, function (exists) {
      if (!exists) {
        console.log('commentHandler insert fail. err = 未找到该帖子数据')
        callback('未找到该帖子记录')
      } else {
        var data = fs.readFileSync(postPath + fileName)

        if (!data.length) {
          data = {}
        } else {
          data = JSON.parse(data)
        }
        if (!commentId) {
          data.comments.push(content)
        } else {
          for (var i = 0; i < data.comments.length; i ++) {
            var commentObj = data.comments[i]
            if (commentObj.id == commentId) {
              commentObj.comments.push(content)
              break;
            }
          }
        }

        //  用户回复帖子动态
        Active.insert(util.createActiveType2(content, data))

        data.commentCount += 1
        data.updatedAt = new Date()
        
        var dataStr = JSON.stringify(data, null, 4)
        fs.writeFile(postPath + fileName, dataStr, function (err) {
          if (err) {
            console.log('commentHandler insert fail. err = ' + err)
            callback('评论失败')
          } else {

            callback(null, data)
          }
        })
      }
    })
  }
}